package com.example.aaaapp.api;

import android.content.Context;
import android.util.Log;

import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Api {

    private static OkHttpClient client;
    private static String requestUrl;

    public static Api api = new Api();
    private static HashMap<String, Object> mParams;

    public Api() {

    }


    public static Api config(String url, HashMap<String, Object> params) {
        client = new OkHttpClient.Builder().build();
        requestUrl = ApiConfig.BaseUrl + url;
        mParams = params;
        return api;
    }

    public void postRequest(Context context, final TtitCallBack callBack) {
        JSONObject jsonObject = new JSONObject(mParams);
        String jsonStr = jsonObject.toString();
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonStr);
        Request request = new Request.Builder().url(requestUrl)
                .addHeader("contentType", "application/json;charset=UTF-8")
                .post(body)
                .build();
        final Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("onFailure", e.getMessage());
                if (callBack != null) {
                    callBack.onFailure(e);
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String resStr = response.body().string();
                Log.e("onResponse", resStr);
                if (callBack != null) {
                    callBack.onSuccess(resStr);
                }
            }
        });
    }



}